<!-- 使用fetch从不同的本地txt文件中请求数据，并数据填充到pre中 -->
<template>
  <div>
    <h1>Fetch starting point</h1>

    <form>
      <label for="verse-choose">Choose a verse</label>
      <select id="verse-choose" name="verse-choose">
        <option>Verse 1</option>
        <option>Verse 2</option>
        <option>Verse 3</option>
        <option>Verse 4</option>
      </select>
    </form>

    <h2>dingdong <em> Please choose a poem that you like</em></h2>

    <pre></pre>
  </div>
</template>
<script>
export default {

  data () {
    return {
    }
  },
  mounted () {
    const verseChoose = document.querySelector("select");
    verseChoose.addEventListener("change", () => {
      const verse = verseChoose.value;
      this.updateDisplay(verse);
    });

    this.updateDisplay("Verse 1");
    verseChoose.value = "Verse 1";
  },
  methods: {
    updateDisplay (verse) {
      const poemDisplay = document.querySelector("pre");
      verse = verse.replace(" ", "").toLowerCase();
      const url = `/files/${verse}.txt`;//http请求根路径即为public下的静态文件
      fetch(url)
        .then((response) => {
          if (!response.ok) {
            throw new Error(`HTTP error: ${response.status}`);
          }
          return response.text();
        })

        .then((text) => {
          poemDisplay.textContent = text;
        })

        .catch((error) => {
          poemDisplay.textContent = `Could not fetch verse: ${error}`;
        });
    }

  }
}
</script>
<style scoped>
html,
pre {
  font-family: sans-serif;
}

body {
  width: 500px;
  margin: 0 auto;
  background-color: #ccc;
}

pre {
  line-height: 1.5;
  letter-spacing: 0.05rem;
  padding: 1rem;
  background-color: white;
}

label {
  width: 200px;
  margin-right: 33px;
}

select {
  width: 350px;
  padding: 5px;
}
</style>